from datetime import datetime

from django.http import JsonResponse
from django.views import View
from rest_framework_jwt.settings import api_settings

from menu.models import SysMenu, SysMenuSerializer
from user.models import SysUser, SysUserSerializer


# 登录
class LoginView(View):
    def post(self, request):
        email = request.POST.get("email")
        password = request.POST.get("password")
        try:
            user = SysUser.objects.filter(email=email, password=password).first()
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 将对象用户传入,获取对象的属性值
            payload = jwt_payload_handler(user)
            # 将属性值编码成jwt格式字符串
            token = jwt_encode_handler(payload)
            # 登录成功时获取用户的角色信息 (去重)
            menu_sql = """SELECT  DISTINCT m.* FROM sys_user u 
            LEFT JOIN sys_user_role ur ON u.id = ur.user_id
            LEFT JOIN sys_role r ON ur.role_id =r.id
            LEFT JOIN sys_role_menu rm ON r.id =rm.role_id
            LEFT JOIN sys_menu m ON rm.menu_id=m.id
            WHERE ur.user_id = """ + str(user.id) + """ ORDER BY   m.order_num, m.parent_id """
            menu_list = SysMenu.objects.raw(menu_sql)
            print(type(menu_list))
            sysMenuList: list[SysMenu] = self.buildTreeMenu(menu_list)
            sys_menu_serializer_list = list()
            for menu in sysMenuList:
                sys_menu_serializer_list.append(SysMenuSerializer(menu).data)

            for item in menu_list:
                print(item.id, item.name)
            return JsonResponse(
                {"code": 200, "token": token, "user": SysUserSerializer(user).data,
                 "menuList": sys_menu_serializer_list, "info": "登录成功！"})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 500, "info": '登陆失败,用户名或密码错误！'})

    # 获取菜单树
    def buildTreeMenu(self, menu_list):
        sys_menu_list: list[SysMenu] = list()
        for item in menu_list:
            for e in menu_list:
                if e.parent_id == item.id:
                    if not hasattr(item, "children"):
                        item.children = list()
                    item.children.append(e)
            if item.parent_id == 0:  # 存入父级菜单
                sys_menu_list.append(item)
        return sys_menu_list


# 修改用户信息
class UpdateUserView(View):
    def post(self, request):
        id = request.POST.get("id")
        username = request.POST.get("username")
        phonenumber = request.POST.get("phonenumber")
        avatar = request.POST.get("avatar")
        email = request.POST.get("email")
        remark = request.POST.get("remark")
        user = SysUser.objects.filter(id=id).first()
        if user is not None:  # 修改用户信息
            user.username = username
            user.phonenumber = phonenumber
            user.email = email
            user.avatar = avatar
            user.remark = remark
            user.update_time = datetime.now().date()
            user.save()
            return JsonResponse({"code": 200, "user": SysUserSerializer(user).data})
        else:
            return JsonResponse({"code": 500, "info": '修改失败'})


# 修改密码
class UpdatePwdView(View):
    def post(self, request):
        type = request.POST.get("type")
        if type == "0":  # 判断是旧密码是否正确
            id = request.POST.get("id")
            oldPassword = request.POST.get("oldPassword")
            # 获取个人信息
            user = SysUser.objects.filter(id=id).first()
            if user.password == oldPassword:
                return JsonResponse({"code": 200, "info": '密码正确'})
            else:
                return JsonResponse({"code": 500, "info": '密码错误'})
        else:  # 更新密码
            id = request.POST.get("id")
            newPassword = request.POST.get("newPassword")
            confirmPassword = request.POST.get("confirmPassword")
            user = SysUser.objects.filter(id=id).first()
            if newPassword == user.password:
                return JsonResponse({"code": 500, "info": '新密码不能与旧密码相同'})
            if newPassword == confirmPassword:  # 密码确认通过后 修改密码
                user.password = newPassword
                user.save()
                return JsonResponse({"code": 200, "info": '修改成功,请重新登录'})
            else:
                return JsonResponse({"code": 500, "info": '两次输入的密码不一致'})
